//
//  MealTableViewController.swift
//  Start Dev in Swift
//
//  Created by ficow on 16/8/16.
//  Copyright © 2016年 ficow. All rights reserved.
//

import UIKit


class MealTableViewController: UITableViewController {

    // MARK: PROPERTIES
    var meals = [Meal]()
    let APP_DID_QUIT_NOTIFICATION = NSNotification.init(name: "APP_DID_QUIT_NOTIFICATION" as NSNotification.Name, object: nil)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = editButtonItem
        editButtonItem.title = "编辑"
        
        if let savedMeals = loadMeals(){
            meals += savedMeals
        }else{
            loadSampleMeals()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(saveMeals), name:APP_DID_QUIT_NOTIFICATION.name, object: nil)
    }

    func loadSampleMeals(){
        let photo1 = UIImage(named: "meal1")!
        let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4)!
        
        let photo2 = UIImage(named: "meal2")!
        let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5)!
        
        let photo3 = UIImage(named: "meal3")!
        let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3)!
        
        meals += [meal1,meal2,meal3]
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return meals.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "MealTableViewCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MealTableViewCell

        let meal = meals[indexPath.row]
        
        cell.nameLabel.text = meal.name
        cell.photoIV.image = meal.photo
        cell.ratingControl.rating = meal.rating
        cell.ratingControl.isUserInteractionEnabled = false

        return cell
    }
 
    @IBAction func unwindToMealList(sender:UIStoryboardSegue){
        
        if let sourceVC = sender.source as? MealViewController,
            let meal = sourceVC.meal{
            
            if let selectedIndexPath = tableView.indexPathForSelectedRow{
                //update existing meal
                meals[selectedIndexPath.row] = meal
                tableView.reloadRows(at: [selectedIndexPath], with: .none)
            }
            else{
                //add new meal
                let newIndexPath = NSIndexPath(row: meals.count, section: 0)
                meals.append(meal)
                tableView.insertRows(at: [newIndexPath as IndexPath], with: .bottom)
            }
        }
    }
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            meals.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }
    
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
        
        //swap(&meals[fromIndexPath.row], &meals[to.row])
        //(meals[fromIndexPath.row],meals[to.row]) = (meals[to.row],meals[fromIndexPath.row])
        if fromIndexPath != to {
            
            let rowObj = meals[fromIndexPath.row]
            meals.remove(at: fromIndexPath.row)
            meals.insert(rowObj, at: to.row)
        }
        
    }
    
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    
    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "ShowDetail"{
            let mealDetailVC = segue.destination as! MealViewController
            if let selectedMealCell = sender as? MealTableViewCell{
                let indexPath = tableView.indexPath(for: selectedMealCell)!
                let selectedMeal = meals[indexPath.row]
                mealDetailVC.meal = selectedMeal
            }
        }
        else if segue.identifier == "AddItem"{
            print("Adding new meal")
        }
    }

    // MARK: NSCODING
    func loadMeals() -> [Meal]?{
        return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal]
    }
    
    func saveMeals(){
        let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path)
        if !isSuccessfulSave{
            print("Failed to save meals")
        }
    }
}
